package com.wlts.wzy.KSOrderModule.util;

import com.alibaba.fastjson.JSON;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.AccessTokenKsMerchantClient;
import com.kuaishou.merchant.open.api.request.KsMerchantItemCategoryRequest;
import com.kuaishou.merchant.open.api.request.KsMerchantOrderListRequest;
import com.kuaishou.merchant.open.api.response.KsMerchantItemCategoryResponse;
import com.kuaishou.merchant.open.api.response.KsMerchantOrderListResponse;
import com.kuaishou.merchant.open.api.response.view.item.MerchantItemCategoryView;
import com.kuaishou.merchant.open.api.response.view.order.MerchantOrderInfoView;
import com.wlts.wzy.KSGoodsModule.entity.KsCategory;
import com.wlts.wzy.KSGoodsModule.service.IKsCategoryService;
import com.wlts.wzy.KSOrderModule.entity.KsOrders;
import com.wlts.wzy.KSOrderModule.service.IKsOrdersService;
import com.wlts.wzy.KSUserModule.entity.KsOauth;
import com.wlts.wzy.KSUserModule.service.IKsOauthService;
import com.wlts.wzy.configBean.KsConfig.KsConfigInfo;
import com.wlts.wzy.configBean.KsConfig.KsConfigTemp;
import com.wlts.wzy.expand.MyLambdaQueryWrapper;
import com.wlts.wzy.util.CopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class KsOrdersUpdate {
    @Autowired
    private IKsOauthService ksOauthService;
    @Autowired
    private IKsOrdersService ksOrdersService;

    @Scheduled(fixedDelay = 300 * 1000)
   // @PostConstruct
    /**
     * 将快手订单更新到本地库
     */
    public void updateOrders(){

        MyLambdaQueryWrapper<KsOauth> ksOauthWrapper = new MyLambdaQueryWrapper<>();

        ksOauthWrapper.eq(KsOauth::getDelFlag, "0");
        ksOauthWrapper.ge(KsOauth::getTokenOverTime, LocalDateTime.now());
        ksOauthWrapper.eq(KsOauth::getTokenStatus, 0);
        List<KsOauth> oauthList = ksOauthService.list(ksOauthWrapper);

        oauthList.forEach(ksOauth -> {
            KsMerchantOrderListRequest orderListRequest = new KsMerchantOrderListRequest();
            orderListRequest.setAccessToken(ksOauth.getAccessToken());
            orderListRequest.setType(1);//订单状态，0未知 1 全部 2 待付款 3 待发货 4 待收货（已发货）5 已收货 6 交易成功订单 7 已关闭订单
            orderListRequest.setCpsType(0);//分销类型 0-全部 1-普通订单 2-分销订单
            orderListRequest.setSort(1);//1时间降序 2时间升序 默认降序
            orderListRequest.setQueryType(2);//1按创建时间查找 2按更新时间查找 默认创建时间

            long end = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();

            int page=1;
            String pcursor=null;

            while (true){
                orderListRequest.setCurrentPage(page);
                orderListRequest.setPageSize(100);
                orderListRequest.setPcursor(pcursor);

                AccessTokenKsMerchantClient tokenKsMerchantClient
                        = new AccessTokenKsMerchantClient("", KsConfigInfo.appKey,KsConfigInfo.signSecret);

                KsMerchantOrderListResponse response = null;
                try {
                    /**
                     * 默认查一天的订单
                     */
                    orderListRequest.setBeginTime(end - 86400000);

                    orderListRequest.setEndTime(end);

                    response = tokenKsMerchantClient.execute(orderListRequest);
                    //降级查一个小时
                    if (response.getResult() == 200015) {
                        orderListRequest.setBeginTime(end - 3600000);
                        response = tokenKsMerchantClient.execute(orderListRequest);
                    }
                    //降级查一分钟
                    if (response.getResult() == 200015) {
                        orderListRequest.setBeginTime(end - 60000);
                        response = tokenKsMerchantClient.execute(orderListRequest);
                    }

                 //   System.out.println(JSON.toJSONString(response));

                    List<MerchantOrderInfoView> orderInfoViews = response.getMerchantOrderListData().getOrderInfoList();

                    List<KsOrders> ksOrdersList=  orderInfoViews.stream().map(a -> {

                        MyLambdaQueryWrapper<KsOrders> orderWrapper=new MyLambdaQueryWrapper<>();
                        orderWrapper.eq(KsOrders::getOid,a.getOid());
                        orderWrapper.eq(KsOrders::getDelFlag,"0");
                        KsOrders orders=ksOrdersService.getOne(orderWrapper);

                        if(orders==null){
                            orders=new KsOrders();
                        }else {
                            a.setAddress(null);
                        }
                        CopyUtils.copyProperties(a,orders);
                        orders.setRemarks(a.getRemark());
                        orders.setOrderProductInfoList(JSON.toJSONString(a.getOrderProductInfoList()));
                        ksOrdersService.saveOrUpdate(orders);
                        return orders;
                    }).collect(Collectors.toList());

//                    if(ksOrdersList.size()>0){
//                        ksOrdersService.saveOrUpdateBatch(ksOrdersList);
//                    }
                    pcursor=response.getMerchantOrderListData().getPcursor();
                    if(pcursor.equals("nomore")){
                        break;
                    }

                } catch (KsMerchantApiException e) {
                    e.printStackTrace();
                    break;
                }
            }

        });

    }


}
